﻿using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using SingleUserMall.Commissions.Form;
using SingleUserMall.Commissions.VO;
using SingleUserMall.Common;
using System.Linq;
using System.Threading.Tasks;

namespace SingleUserMall.Commissions
{
    [AbpAuthorize]
    public class CommissionManageAppService : SingleUserMallAppServiceBase, ICommissionManageAppService
    {
        private readonly IRepository<Commission,long> _commissionRepository;
        public CommissionManageAppService(IRepository<Commission, long> commissionRepository)
        {
            _commissionRepository = commissionRepository;
        }
        public async Task<CommissionVO> GetCommissionAsync(SingleId<long> form)
        {
            var commission = await _commissionRepository.FirstOrDefaultAsync(form.Id);
            return commission.ToVO<Commission, CommissionVO>((w, vo) =>
            {
                vo.FirstCommissionView = ((int)(w.FirstCommission * 100)).ToString();
                vo.SecondCommissionView = ((int)(w.SecondCommission * 100)).ToString();
            });
        }

        public async Task<PagedResultDto<CommissionVO>> GetCommissionsAsync(PagedForm form)
        {
            var query = _commissionRepository.GetAll()
                .OrderByDescending(x => x.CreationTime);
            return await query.ToPagedResultDtoAsync<Commission, CommissionVO>(form,(w,vo)=>
            {
                vo.FirstCommissionView = ((int)(w.FirstCommission * 100)).ToString();
                vo.SecondCommissionView = ((int)(w.SecondCommission * 100)).ToString();
            });
        }

        public async Task SaveCommissionAsync(CommissionForm form)
        {
            var commission = await _commissionRepository.FirstOrDefaultAsync(form.Id);
            if (commission != null)
            {
                commission = form.MapTo(commission);
                await _commissionRepository.UpdateAsync(commission);
            }
            else
            {
                commission = form.MapTo<Commission>();
                await _commissionRepository.InsertAsync(commission);
            }
        }
    }
}
